<?php
/**
 * User: 五哥派
 * Date: 2024/7/1
 * Tel(同WX): 17335592719
 */
namespace app\api\controller\v1;

use app\api\controller\ApiBase;
use app\api\model\user\UserAddress as UserAddressModel;
use app\api\service\user\User as UserService;

class Address extends ApiBase {

    protected $model;

    public function __construct(UserAddressModel $model){

        parent::__construct();
        $this->model = $model;

    }


    /**
     * 根据id获取用户地址信息
     */
    public function getDetail(){
        $id = $this->request->get('id');
        $userId = UserService::getCurrentLoginUserId();
        $userAddress = $this->model->findData(['id' => $id, 'user_id' => $userId]);
        if(!$userAddress){
            return error('用户地址不存在');
        }
        return success('获取成功', ['detail' => $userAddress]);
    }

    public function getList(){
        $list = $this->model->queryData();
        if (empty($list)) {
            return error('查询失败');
        }
        return success('查询成功', ['list' => $list]);
    }

    /**
     * 获取默认详情
     */
    public function getDefault(){
        $userId = UserService::getCurrentLoginUserId();
        $userAddress = $this->model->findData(['user_id' => $userId, 'is_default' => 1]);
        if(!$userAddress){
            return error('默认地址不存在');
        }
        return success('获取成功', ['detail' => $userAddress]);
    }

    /**
     * 新增用户收获地址
     */
    public function add(){
        $addressInfo = $this->request->post('addressInfo/a');
        $userId = UserService::getCurrentLoginUserId();

       /* //查询是否存在默认地址，不存在则直接为默认，存在则不理会
        $address = $this->model->findData(['user_id' => $userId, 'is_default' => 1]);
        if(!$address){
            $addressInfo['is_default'] = 1;
        }*/
        $addressInfo['user_id'] = $userId;
        $res = $this->model->saveData($addressInfo, false);
        if (!$res) {
            return error('保存失败');
        }

        return success('保存成功');
    }

    public function edit(){
        $addressInfo = $this->request->post('addressInfo/a');
        $userId = UserService::getCurrentLoginUserId();
        $addressInfo['user_id'] = $userId;
        $res = $this->model->saveData($addressInfo, true);
        if (!$res) {
            return error('保存失败');
        }

        return success('保存成功');
    }


    public function delete(){
        $id = $this->request->post('id');
        $res = $this->model->delDataByID($id);
        if (!$res) {
            return error('删除失败');
        }

        return success('删除成功');
    }


    public function setDefault(){
        $id = $this->request->post('id');

        $userId = UserService::getCurrentLoginUserId();
        $this->model->saveData(['is_default' => 0], true, ['user_id' => $userId]);

        $addressInfo['is_default'] = 1;
        $res = $this->model->updateById($id, $addressInfo);
        if (!$res) {
            return error('设置失败');
        }
        return success('设置成功');
    }



}